import React, { useState, useMemo, useEffect, useReducer } from "react";
import "./index.scss";
import "./task.scss";
import { Button, Card, Tabs, Popup, Skeleton, Empty, Ellipsis, Dialog } from "antd-mobile";
import {
    pdfSignTask_query_page,
    pdfSealTask_query_page,
    findAppointUnFinishRecord,
} from "src/api/home";
import { pqsstartWkInfo_query_one, getPdfInfo } from "src/api/pqsstartWkInfo";
import { RightOutline } from "antd-mobile-icons";
import BetterScroll from "pages/components/betterScroll";
import { locationShape, historyShape, storeShape } from "src/propType";
import { PDF_URL, FILE_VIEW, FILE_VIEW_ONLINE } from "src/config";
import { PreviewPdf } from "src/utils/index";
import Cookies from "js-cookie";
import axios from "src/api/index";
import PropTypes from "prop-types";
import Toast from "src/pages/components/clickableToast";

const tabList = [
    {
        title: "待办",
        key: "0",
    },
    {
        title: "待签名",
        key: "1",
    },
    // {
    //     title: "签章列表",
    //     key: "2",
    // },
];

const page = 1,
    limit = 150;

function taskListReducer(state, action) {
    switch (action.type) {
        case "signList": {
            return {
                ...state,
                signList: action.signList,
                loading: action.loading,
            };
        }
        case "sealList": {
            return {
                ...state,
                sealList: action.sealList,
            };
        }
        case "otherMsg": {
            return {
                ...state,
                otherMsg: action.otherMsg,
            };
        }
        case "activityKey": {
            return {
                ...state,
                activityKey: action.activityKey,
            };
        }
    }
}

const taskListState = { signList: [], sealList: [], otherMsg: [], loading: true, activityKey: "0" };

const TaskList = props => {
    const [taskList, setTaskList] = useReducer(taskListReducer, taskListState);
    const [visible, setVisible] = useState(false);
    const { store, history, setCount } = props;
    const beanName = "pqs-" + store.user.userData.projId;

    const getSignTask = () => {
        pdfSignTask_query_page(page, limit, beanName).then(res => {
            if (res.success) {
                setTaskList({
                    type: "signList",
                    signList: res.data,
                    loading: false,
                });
            }
        });
    };

    const getSealTask = () => {
        pdfSealTask_query_page(page, limit, beanName).then(res => {
            if (res.success) {
                setTaskList({
                    type: "signList",
                    signList: res.data,
                });
            }
        });
    };

    const getDataList = () => {
        findAppointUnFinishRecord().then(res => {
            if (res.success) {
                // 过滤掉业务表不存在的待办数据
                let otherMsg = res.data.filter(other => {
                    return other.title && other.title != null && other.title !== "";
                });
                matchFiledFun(otherMsg);
            }
        });
    };

    const getMenuListArr = (tree, arr) => {
        tree.forEach(item => {
            arr.push(item);
            if (item.data) {
                getMenuListArr(item.data, arr);
            }
        });
        return arr;
    };

    const matchFiledFun = otherMsg => {
        const menuListArray = getMenuListArr(store.user.menuList, []);
        menuListArray.forEach(menuOne => {
            otherMsg.forEach(item => {
                if (item.tableId == menuOne.tableId) {
                    item.model = "other";
                    item.treePath = menuOne.url;
                    item.treeName = menuOne.treeName;
                    item.jspath = menuOne.jspath;
                }
            });
        });
        setTaskList({
            type: "otherMsg",
            otherMsg,
        });
    };

    useEffect(() => {
        getSignTask();
        // getSealTask();
        getDataList();
    }, []);

    useEffect(() => {
        if (setCount) {
            const count =
                taskList.sealList.length + taskList.signList.length + taskList.otherMsg.length;
            setCount(count);
        }
    }, [taskList.sealList, taskList.signList, taskList.otherMsg]);

    const changeTab = activityKey => {
        setTaskList({
            type: "activityKey",
            activityKey,
        });
    };

    const currenTabList = useMemo(() => {
        const { activityKey, signList, sealList, otherMsg } = taskList;
        const count = signList.length + sealList.length + otherMsg.length;
        switch (activityKey) {
            case "1":
                return {
                    activityKey,
                    dataSource: signList,
                    count,
                };
            case "2":
                return {
                    activityKey,
                    dataSource: sealList,
                    count,
                };
            default:
                return {
                    activityKey,
                    dataSource: otherMsg,
                    count,
                };
        }
    }, [taskList]);

    const title = record => {
        const tipString = "需要审核，请及时处理!";
        let titleString = "";
        switch (taskList.activityKey) {
            case "1":
                titleString = record.name;
                break;
            case "2":
                titleString = record.tableName || record.name;
                break;
            default:
                titleString = record.moduleName;
        }

        // return (
        //     <>
        //         <span className="title">【{titleString}】</span>
        //         <span>{tipString}</span>
        //     </>
        // );

        return titleString;
    };

    const getDetail = record => {
        const { businesskey, jspath, treeName } = record;
        businesskey && history.push(`${jspath}/detail?page=sign&kid=${businesskey}&title=${decodeURIComponent(treeName)}`);
    };

    const viewDetail = record => {
        if (currenTabList.activityKey === "0") {
            record.businesskey && getDetail(record);
        }
        if (currenTabList.activityKey === "1") {
            history.push("/SignTask");
        }
    };

    const toViewPdf = async kid => {
        const isView = await Dialog.confirm({ content: "是否查看文件" });
        if (!isView) return;

        Toast.show({
            icon: "loading",
            content: "",
            duration: FILE_VIEW_ONLINE ? 2000 : 0,
        });
        const res = await getPdfInfo(kid);
        const { code, data, msg } = res;
        const hasFile = data && Array.isArray(data) ? data.length : data;
        if (code === 200 && hasFile) {
            const fileUrl = data && (data.pdfName || data.pdfPath || data.svrFullPath);
            const url = (PDF_URL + fileUrl).replace(/\\/g, "/");

            if (FILE_VIEW_ONLINE) {
                // 在线预览方式
                // let viewUrl = `${url}&fullfilename=${kid}.pdf&isApp=1`;
                PreviewPdf(fileUrl);
            } else {
                //downLoadFile
                axios({
                    method: "GET",
                    customError: true,
                    _ingore: true,
                    url: FILE_VIEW,
                    params: {
                        fileName: `${kid}.pdf`,
                        cookies: `CRBIMSSOJWT=${Cookies.get("CRBIMSSOJWT")}`,
                        url,
                        isApp: 1,
                    },
                }).then(res => {
                    if (res.msg === "SUCCESS") {
                        Toast.show({
                            icon: "success",
                            content: "",
                        });
                        res.data && window.open(res.data);
                    } else {
                        Toast.show({
                            icon: "fail",
                            content: res.msg,
                        });
                    }
                });
            }
        } else {
            Toast.show({
                icon: "fail",
                content: hasFile ? msg : "PDF文件不存在",
                afterClose: () => {},
            });
            return;
        }
    };

    const hasData = currenTabList?.dataSource?.length;

    return (
        <div className="task">
            <Tabs activeKey={taskList.activityKey} onChange={changeTab}>
                {tabList.map(tab => {
                    return <Tabs.Tab title={tab.title} key={tab.key} />;
                })}
            </Tabs>
            <div className="task-content">
                <BetterScroll>
                    <ul className="task-content-list">
                        {taskList.loading ? (
                            <Skeleton.Paragraph lineCount={10} animated />
                        ) : hasData ? (
                            currenTabList.dataSource.map((record, i) => {
                                const key = record.taskId || record.signsKid || i;
                                const date = record.startTime || record.userSignDate;
                                // return <li key={key}>{title(record)}</li>;
                                return (
                                    <li key={key}>
                                        <h3 className="header" onClick={e => viewDetail(record)}>
                                            {/* <span>{title(record)}</span> */}
                                            <Ellipsis
                                                className="content"
                                                direction="end"
                                                content={title(record)}
                                            />
                                            <span className="logo">
                                                <RightOutline />
                                            </span>
                                        </h3>
                                        {/* <div className="content"></div> */}
                                        <Ellipsis
                                            className="content"
                                            direction="end"
                                            content={`您有一条${title(
                                                record,
                                            )}表单待审核, 请及时查看处理。`}
                                        />
                                        <div
                                            className="blue"
                                            onClick={e => {
                                                const kid = record.businesskey || record.recordId;
                                                kid && toViewPdf(kid);
                                            }}
                                        >
                                            查看文件
                                        </div>
                                        <div
                                            className="blue"
                                            onClick={e => {
                                                const kid = record.businesskey || record.recordId;
                                                kid && history.push(`/FileInfo?${kid}`);
                                            }}
                                        >
                                            查看附件
                                        </div>
                                        <div className="footer">
                                            {taskList.activityKey === "1"
                                                ? date?.substring(0, 10)
                                                : date}
                                        </div>
                                    </li>
                                );
                            })
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </ul>
                </BetterScroll>
            </div>
        </div>
    );
};

TaskList.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
    setCount: PropTypes.func,
};

export default TaskList;
